package com.me.chat.util;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.me.chat.util.img.ImageUtil;
import com.me.chat.util.img.ImgColorGet;
import com.me.chat.util.img.TinyImgUtil;
import com.me.chat.util.img.gif.GifUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

/**
 * FastDFS客户端包装类
 * @Author: qiu
 */
@Component
public class FastDFSClientUtil {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 正常大小的 文件上传
     * @param file
     * @param isSmall 是否为缩略图
     * @param scale //缩放比例，如果isSmall 是false 这个参数可以是空
     * @param quality //缩放质量，如果isSmall 是false 这个参数可以是空
     * @return 文件路径
     * @throws IOException
     */
    public String uploadFile(MultipartFile file, Boolean isSmall,Double scale,Double quality) throws IOException {
        if (file != null) {

            byte[] bytes = file.getBytes();
            //文件大小 得到的size是比特
            long fileSize = file.getSize();
            String originalFilename = file.getOriginalFilename();
            //扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            if(isSmall == false){
                //得到图片路径
                String path = this.uploadFile(bytes, fileSize, extension);

                return path;
            }
            else {
                //生成 缩略图 如果不是gif格式
                if(!"gif".equals(extension)){
                    ByteArrayOutputStream tinyByteStream = TinyImgUtil.generateScale(bytes,extension,scale,quality);
                    int tinySize = tinyByteStream.size();
                    byte[] tinyBytes = tinyByteStream.toByteArray();

                    String path = this.uploadFile(tinyBytes, tinySize, extension);
                    return path;
                }else {
                    Double imageHeight = ImageUtil.getImageHeight(file)*scale;
                    Double imageWidth = ImageUtil.getImageWidth(file)*scale;

                    int width = imageWidth.intValue();
                    int height = imageHeight.intValue();
                    ByteArrayOutputStream generateGif = GifUtil.generateGif(bytes, width, height);

                    int gifSize = generateGif.size();
                    byte[] gifBytes = generateGif.toByteArray();

                    String path = this.uploadFile(gifBytes, gifSize, extension);
                    return path;
                }

            }

        }
        return null;
    }

    /**
     * 文件上传 ，自定缩略图像素大小与质量  专用于头像上传
     * @param file
     * @param width
     * @param height
     * @param quality
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file,int width,int height,double quality) throws IOException {
        if (file != null) {

            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            // 生成 缩略图  自定义大小
            ByteArrayOutputStream tinyByteStream = TinyImgUtil.generateScale(bytes,extension,width,height,quality);
            int tinySize = tinyByteStream.size();
            byte[] tinyBytes = tinyByteStream.toByteArray();

            return this.uploadFile(tinyBytes, tinySize, extension);

        }
        return null;
    }

    /**
     * 文件上传 ，自定缩略图百分比大小与质量
     * @param file
     * @param scale
     * @param quality
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file,double scale,double quality) throws IOException {

        if (file != null) {

            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            /**
             * 生成 缩略图  自定义大小
             */
            ByteArrayOutputStream tinyByteStream = TinyImgUtil.generateScale(bytes,extension,scale,quality);
            int tinySize = tinyByteStream.size();
            byte[] tinyBytes = tinyByteStream.toByteArray();

            return this.uploadFile(tinyBytes, tinySize, extension);

        }
        return null;
    }


    /**
     * 文件上传
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     * @return 返回文件路径（卷名和文件名）
     */
    private String uploadFile(byte[] bytes, long fileSize, String extension) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        /**
         * 元数组，这个参数会在文件上传的时候生成一个 -m文件 例如.jpeg-m
         */
        Set<MetaData> metaDataSet = new HashSet<MetaData>();
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));
        StorePath storePath = null;
        storePath = fastFileStorageClient.uploadFile(bais, fileSize, extension, metaDataSet);

        return storePath.getFullPath();
    }



    /**
     * 下载文件
     * @param urlPath 文件url路径
     * @return 文件字节
     * @throws IOException
     */
    public  byte[] downloadFile(String urlPath) throws IOException {

        //解析路径
        URL url = new URL(urlPath);
        String host = url.getPath();
        //去掉得到的path路径去掉第一个 ”/“
        String filePath = host.substring(1);

        byte[] bytes = null;
        if (StringUtils.isNotBlank(filePath)) {
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            DownloadByteArray byteArray = new DownloadByteArray();
            //得到byte 数组
            bytes = fastFileStorageClient.downloadFile(group, path, byteArray);
        }

        return bytes;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public void deleteFile(String filePath) {
        if (StringUtils.isNotBlank(filePath)) {
            fastFileStorageClient.deleteFile(filePath);
        }
    }
}